<script setup lang="ts">
import { ref, computed, onBeforeUnmount } from "vue";
import { useStore } from "@/stores/data";
import { dialog } from '@/utils/dialog'

const store = useStore();

const confirmPassword = ref(''); 
const isRadio = ref(false)
const isView = ref(false)
const errorMessage = ref('') 

const view = () => {
  isView.value = !isView.value
}

const radioTap = () => {
  isRadio.value = !isRadio.value
}

// ===== 倒计时状态 =====
const COUNTDOWN = 60;
const remain = ref(0);        // 剩余秒数，0 表示可再次发送
const sending = ref(false);   // 接口请求中的瞬时状态
let timerId: number | null = null;

const phoneOk = computed(() => {
  const p = store.register?.phone?.trim() || "";
  return p.length >= 6; // 如需严格校验可换为正则
});

// 验证手机号
const validatePhoneNumber = (phone: string) => {
  const regex = /^1[3456789]\d{9}$/
  return regex.test(phone)
}

const canSend = computed(() => {
  // return !!store.register && phoneOk.value && !sending.value && remain.value === 0;
  return validatePhoneNumber(store.register.phone)
});

const btnText = computed(() => {
  return remain.value > 0 ? `${remain.value}s 后重试` : "获取验证码";
});

function startCountdown() {
  remain.value = COUNTDOWN;
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }
  timerId = window.setInterval(() => {
    if (remain.value <= 1) {
      remain.value = 0;
      if (timerId) {
        clearInterval(timerId);
        timerId = null;
      }
    } else {
      remain.value -= 1;
    }
  }, 1000);
}

onBeforeUnmount(() => {
  if (timerId) clearInterval(timerId);
  timerId = null;
});

// ===== 获取验证码 =====
const getCode = async () => {
  if (!canSend.value) return;
  try {
    sending.value = true;
    const res = await store.getCodeAct(store.register.phone.toString(), "register");
    console.log(res);
    startCountdown(); // 成功后开始倒计时
  } catch (error) {
    console.log(error);
    // 失败不启动倒计时，允许再次点击
  } finally {
    sending.value = false;
  }
};

// ===== 注册（保持你原逻辑） =====
const doRegister = async () => {
  // 清除之前的错误信息
  errorMessage.value = ''

  // 表单验证
  if (!isRadio.value) {
    errorMessage.value = '请先同意用户协议和隐私政策'
    return
  }

  if (!store.register.phone || !/^1[3-9]\d{9}$/.test(store.register.phone)) {
    errorMessage.value = '请输入正确的手机号'
    return
  }

  if (!store.register.code) {
    errorMessage.value = '请输入验证码'
    return
  }

  if (store.register.password !== confirmPassword.value) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  if (!store.register.invite_code) {
    errorMessage.value = '请输入邀请码'
    return
  }

  try {
    store.register.phone = store.register.phone.toString()
    store.register.code = store.register.code.toString()
    store.register.invite_code = store.register.invite_code.toString()
    await store.registerAct().then(res => {
      dialog.alert({ iconType: 'sc', message: '注册成功', showCustom: true, onConfirm: () => {window.location.reload();} });
    });
  } catch (e) {
    console.log(e);
  }
};
</script>

<template>
  <!-- 注册 -->
  <div class="register-form">
    <div class="form-content">
      <div class="item">
        <div class="item-title">手机号</div>
        <div class="input-block">
          <input
            class="item-input"
            type="number"
            v-model="store.register.phone"
            placeholder="请输入手机号"
          />
        </div>
      </div>

      <div class="item">
        <div class="item-title">验证码</div>
        <div class="input-block verification-code">
          <input
            class="item-input"
            type="number"
            v-model="store.register.code"
            placeholder="请输入验证码"
          />
          <button class="code-button" :disabled="!canSend" @click="getCode">
            {{btnText}}
          </button>
        </div>
      </div>

      <div class="item">
        <div class="item-title">密码</div>
        <div class="input-block">
          <input
            v-show="!isView"
            class="item-input"
            type="password"
            v-model="store.register.password"
            placeholder="请输入密码"
          />
          <input
            v-show="isView"
            class="item-input"
            type="text"
            v-model="store.register.password"
            placeholder="请输入密码"
          />
          <div class="icon" :class="{ active: isView }" @click="view"></div>
        </div>
      </div>

      <div class="item">
        <div class="item-title">确认密码</div>
        <div class="input-block">
          <input
            class="item-input"
            type="password"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
          />
        </div>
      </div>

      <div class="item">
        <div class="item-title">邀请码</div>
        <div class="input-block">
          <input
            class="item-input"
            type="number"
            v-model="store.register.invite_code"
            placeholder="请输入邀请码"
          />
        </div>
      </div>

      <div class="button-block">
        <button class="button" @click="doRegister">注册</button>
      </div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
    </div>

    <div class="protocol">
      <div class="protocol-radio" :class="{ active: isRadio }" @click="radioTap"></div>
      <div class="protocol-text">
        已同意并阅读 <span>用户协议</span>与 <span>隐私政策</span>
      </div>
    </div>
  </div>
</template>

<style>
  @import url(./index.scss);
</style>